package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import splug.cjk.packet.FriendPacket;

public class ReportWrite extends Thread {

	private InputStream is;
	private OutputStream os;
	
	
	public ReportWrite(InputStream is, OutputStream os) {
		super();
		this.is = is;
		this.os = os;
	}


	@Override
	public void run() {
		super.run();
		try {
			//신고한 사람의 아이디와 신고 할 사람의 아이디, 신고사유를 가져온다
			ObjectInputStream input = new ObjectInputStream(is);
			FriendPacket packet = (FriendPacket) input.readObject();
			String id = packet.getId();
			String you = packet.getYou();
			String reason = packet.getFriend_list().get(0);
			
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/carpool?useUnicode=true&characterEncoding=euckr","root","apmsetup");
			Statement stmt = conn.createStatement();
			
			//이미 신고 한적이 있는지 검사한다
			String query2 = "select id, you from report";

			ResultSet rs = stmt.executeQuery(query2);

			while(rs.next()){
				String str1 = rs.getString("id");
				String str2 = rs.getString("you");
				//이미 신고 한 적이 있으면 2번을 보내준다
				if(str1.equals(id) && str2.equals(you)){
					os.write('2');
					os.flush();
					return;
				}
			}
			
			//해당하는 회원이 있는지 검사한다
			String query1 = "select id from member;";

			rs = stmt.executeQuery(query1);

			while(rs.next()){
				String str = rs.getString("id");
				if(str.equals(you)){
					String query = "INSERT INTO `report` (`idtreat`, `id` ,`you` ,`reason`) " +
					"VALUES (0, '" + id + "','" + you + "','" + reason + "');";

					stmt.execute("SET CHARACTER SET euckr");
					stmt.execute("set names euckr");

					stmt.executeUpdate(query);

					os.write('1');
					os.flush();
					return;
				}

			}

			//해당하는 회원이 없으면 '0'번 응답을 보내준다
			os.write('0');
			os.flush();
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
